package com.guoning.office_system.controller;

//import com.guoning.office_system.model.File;
import com.guoning.office_system.model.User;
import com.guoning.office_system.model.WorkOrder;
import com.guoning.office_system.service.FileService;
import com.guoning.office_system.utils.Constants;
import com.guoning.office_system.utils.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    FileService fileService;

    /**
     * 获取工单文件
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/selectByOrderId")
    public JsonResult selectByOrderId(@RequestParam("workOrderId") Long orderId){
        JsonResult jsonResult;
        try {
            List list = fileService.selectByOrderId(orderId);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "获取工单文件成功", list);
        }catch (Exception e){
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "获取工单文件异常");
        }
        return jsonResult;
    }

    @RequestMapping(value = "/uploadOrderFile", method = RequestMethod.POST)
    public JsonResult uploadOrderFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] files,
                                      @RequestParam("userId") Long userId,
                                      @RequestParam("startTime") String startTime,
                                      @RequestParam("endTime") String endTime,
                                      @RequestParam("orderTitle") String orderTitle,
                                      @RequestParam("orderContent") String orderContent){
        JsonResult jsonResult;
        List list = new ArrayList();
        User user = getUserDate(request);
        String filePath = "/data/file";
//        String filePath = "F:\\郭凝\\";
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            if (file.isEmpty()) {
                jsonResult = new JsonResult(Constants.STATUS_FAIL, "上传第" + (i++) + "个文件失败");
                return jsonResult;
            }
            com.guoning.office_system.model.File sqlFile = new com.guoning.office_system.model.File();
            String fileName = file.getOriginalFilename();
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            String newFileName =  id + fileName.substring(fileName.lastIndexOf('.'));

            sqlFile.setId(id);
            sqlFile.setFilePath(filePath + newFileName);
            sqlFile.setFileSize(String.valueOf(file.getSize()));
            sqlFile.setFileName(fileName);
            File dest = new File(filePath + newFileName);
            try {
                file.transferTo(dest);
                list.add(sqlFile);
                logger.info("第" + (i + 1) + "个文件上传成功");
            } catch (IOException e) {
                logger.error(e.toString(), e);
                jsonResult = new JsonResult(Constants.STATUS_ERROR, "上传第" + (i++) + "个文件失败");
                return jsonResult;
            }
        }
        try {
            WorkOrder workOrder = new WorkOrder();
            workOrder.setUserId(userId);
            workOrder.setOrderTitle(orderTitle);
            workOrder.setOrderContent(orderContent);
            workOrder.setStartTime(new Date(startTime));
            workOrder.setEndTime(new Date(endTime));
            Long workOrderId = fileService.insert(workOrder,list, user);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "下发成功", workOrderId);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "下发异常");
        }
        return jsonResult;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public JsonResult upload(HttpServletRequest request, @RequestParam("file") MultipartFile file){
        JsonResult jsonResult;
        if(file.isEmpty()){
            jsonResult = new JsonResult(Constants.STATUS_FAIL, "上传失败");
            return jsonResult;
        }
        User user = getUserDate(request);
                String filePath = "/data/file/";
//        String filePath = "F:\\郭凝\\";
        String fileName = file.getOriginalFilename();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName =  id + fileName.substring(fileName.lastIndexOf('.'));
        com.guoning.office_system.model.File sqlFile = new com.guoning.office_system.model.File();
        sqlFile.setId(id);
        sqlFile.setFilePath(filePath + newFileName);
        sqlFile.setFileSize(String.valueOf(file.getSize()));
        sqlFile.setFileName(fileName);
        File dest = new File(filePath + newFileName);
        try {
            file.transferTo(dest);
            logger.info("上传成功");
            fileService.insertOne(sqlFile, user);
            Map map = new HashMap();
            map.put("fileId", sqlFile.getId());
            map.put("fileUrl", "https://www.layoom.top/file/" + newFileName);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS, "上传成功", map);
        } catch (IOException e) {
            logger.error(e.toString(), e);
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "上传异常");
        }
        return jsonResult;
    }

    @RequestMapping(value = "/download")
    public String downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response){
        com.guoning.office_system.model.File sqlFile = fileService.selectByPrimaryKey(fileId);
        if (sqlFile != null) {
            String fileName = sqlFile.getFileName();// 文件名
            //设置文件路径
            File file = new File(sqlFile.getFilePath());
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}
